<?php

class MAIN {
    
    protected $_table;
    protected $_conn;
    protected $_key = array();
    protected $_id  = array();
    protected $_vars  = array();
    protected $_columns = array();
    
    public function __construct($table = false, $key = false, $id = 0, $columns=false) {
        
        $this->getDBConnection();        
        $this->_table = $table;
        $this->_key   = $key;
        $this->_id    = $id;
        $this->_columns = $columns;
    
        if ($table && $key && $id) $this->selectRow();
        else if ($table) $this->loadRow();
    }
    
    public function getDBConnection() {
        $mysql       = MYSQL::getInstance();
        $this->_conn = $mysql->dbh;        
    }
    
    public function getVar($key) {
        return $this->_vars[$key];
    }

    public function setVar($key, $val='') {
        $this->_vars[$key] = trim($val);
    }

    public function refreshObj() {
        $this->selectRow();
    }

    public function deleteRow($id = 0) {
            $id = ($id > 0) ? $id : $this->_id;
            $prepared = $this->_conn->prepare("DELETE FROM $this->_table WHERE $this->_key = :id");           
            $result   = $prepared->execute(
                    array (
                        'id' => $id
                    )
            );
        return $prepared;         
    }
    
    public function saveArray($data = array()) {
        if (!empty($data))
        {
            foreach ($data as $key => $value) {
                $this->setVar($key, $value);
            }
            return $this->saveRow();
        }
    }
    
    public function saveRow() {
        if ($this->_id > 0 || $this->selectRow) return $this->updateRow();
        else return $this->insertRow();
    }   
    
   
    public function insertRow() {
		
        $fields = $this->prepareFields();
        
	    if (!empty($fields))
        {
            $prepared = $this->_conn->prepare("INSERT INTO $this->_table SET $fields");
            $result   = $prepared->execute($this->_vars);
            return $this->_conn->lastInsertId();             
        }
    }
  
    public function fetchRow($identifer,$col="*",$sub_table=false){
      $sub_table = $sub_table?$sub_table:  $this->_table;
      $fields= NULL; 
      foreach ($identifer as $key => $value) {                  
         $fields .= $key. "='" .$value. "' AND ";                          
      }
      $fields = rtrim(rtrim($fields), 'AND');
      
      $prepared = $this->_conn->prepare("SELECT $col FROM $sub_table WHERE $fields ");  
      //echo "SELECT * FROM $sub_table WHERE $fields ";
      $prepared->execute();
                
      return $prepared;    
    }
    
    protected function selectRow($columns=false) {
            $this->loadRow();
            
            $columns = $columns ? $this->prepareColumns() : "*";
            $prepared = $this->_conn->prepare("SELECT $columns FROM $this->_table WHERE $this->_key = :id");
            $result   = $prepared->execute(
                    array (
                        'id' => $this->_id
                    )
            );
            $values = $prepared->fetch(PDO::FETCH_ASSOC);
            foreach ($this->_vars as $key => $val) {
                $this->setVar($key, $values[$key]);
            }
        return $prepared;         
    }
    
    private function loadRow($id = 0) {
            $id       = ($id > 0) ? $id : $this->_id;
             
            $prepared = $this->_conn->prepare("SHOW COLUMNS FROM $this->_table");
            $result   = $prepared->execute();        
            
            if($this->_columns)
               {
                    foreach($this->_columns as $cols)
                    {
                          $this->setVar($cols);
                    }
               }
               else
               {
                     while ($row = $prepared->fetch())
                     {
                        $this->setVar($row['Field']);
                     }
               } 
    }

    public function fetchObj($id=0, $columns='*') {
            $id = ($id > 0) ? $id : $this->_id;
            $prepared = $this->_conn->prepare("SELECT $columns FROM $this->_table WHERE $this->_key = :id");
            $result   = $prepared->execute(
                    array (
                        'id' => $id
                    )
            );        
        return $prepared;
    }
 // */
    protected function insertMultipleValues($table, $array) {
            $values = '';
            if (is_array($array))
            {    
                foreach ($array as $row)
                {
                    $values .= 'VALUES (';
                    foreach ($row as $val) {
                        $values .= "'$val', ";
                    }
                    $values  = rtrim(trim($values), ',') .'),';
                }       
            }

            if (is_array($array) && !empty($values))
            {
                 $prepared = $this->_conn->prepare("INSERT INTO $table(" .  implode(',', array_keys($array[0])). ") " .rtrim($values, ','). ';');
                 $result   = $prepared->execute();       
            }
    }
        

    private function updateRow() {
		
        $fields = $this->prepareFields(1);
		if (!empty($fields))
        {
            $prepared = $this->_conn->prepare("UPDATE $this->_table SET $fields WHERE $this->_key =:$this->_key");
            $result   = $prepared->execute($this->_vars);
            return $this->getVar($this->_key);             
        }        
    }    
    
    private function prepareFields($flag=0) {
        $fields = '';
        foreach ($this->_vars as $key => $value) {
            if ($flag && !($key == $this->_key))
            {
                $fields .= $key. '=:' .$key. ', ';                
            }
            else if(!$flag) $fields .= $key. '=:' .$key. ', ';
        }
        return rtrim(rtrim($fields), ',');
    }       
    
    
  private function prepareColumns($flag=0)
        {
           $cols = '';
           foreach($this->_columns as $column)
               {
                 $cols .= $column . ',';
               }
               
            return rtrim(rtrim($cols),',');
        }  
    
    public function last_insert_id() {
        return $this->_conn->lastInsertId();          
    }
    
    
         
    public function fetchData($table,$clause,$col='*'){
       $prepared = $this->_conn->prepare("SELECT $col FROM $table $clause ");       
       $result = $prepared->execute(
                        array(
                            'table' => $table,'clause'=>$clause,'col'=>$col
                        )
                );         
       return $prepared;     
    }
    
    
         
    
}

